from line import Line
from arrangement import Arrangement

#Class that holds a set of lines.
class Segments(object):
    def __init__(self, name = ""):
        self._arr = []
        self._name = name
    def __str__(self):
        name = " \"" + self.name + "\"" if self.name != "" else ""
        return "<" + self.__class__.__name__ + "%s [%d]:\n" % (name, len(self)) + "\n".join(["  " + str(x) for x in self]) + "\n>"
    def __repr__(self):
        name = " \"" + self.name + "\"" if self.name != "" else ""
        return "<" + self.__class__.__name__ + "%s [%d]>" % (name, len(self))
    def __getitem__(self, index):
        return self._arr[index]
    def add(self, line):
        self._arr.append(line)
    def __len__(self):
        return len(self._arr)
    @property
    def name(self):
        return self._name
    def __iter__(self):
        class SegmentsIter(object):
            def __init__(self, segments):
                self._segments = segments
                self._index = -1    
            def __iter__(self):
                return self
            def next(self):
                if self._index < len(self._segments) - 1:
                    self._index += 1
                    l = self._segments[self._index]
                    assert isinstance(l, Line)
                    return l
                else:
                    raise StopIteration()
        return SegmentsIter(self)
    def __contains__(self, item):
        return item in self._arr
    @property
    def intersections(self):
        arr = Arrangement()
        line_previous = None
        last_point = None
        for line in self:
            assert isinstance(line, Line)
            if (not line_previous):
                line_previous = line
                continue
            intersection_point = line_previous.intersect(line)
            if (intersection_point not in arr):
                arr.add(intersection_point)
                last_point = intersection_point
            line_previous = line
        line = self[0]
        intersection_point = line_previous.intersect(line)
        if (intersection_point not in arr):
            arr.add(intersection_point)
            last_point = intersection_point
        return arr
